import React from 'react';
import { getDisplayTimeBySeconds } from './utils';

export default function Duration(props) {
    const { audio } = props;
    const [duration, setDuration] = React.useState(0);

    const handleAudioCurrentTimeChange = e => {
        setDuration(e.target.duration);
    };

    React.useEffect(() => {
        setDuration(audio.duration);
        audio.addEventListener('durationchange', handleAudioCurrentTimeChange);
        audio.addEventListener('abort', handleAudioCurrentTimeChange);
        return () => {
            audio.removeEventListener('durationchange', handleAudioCurrentTimeChange);
            audio.removeEventListener('abort', handleAudioCurrentTimeChange);
        };
    }, [audio]);

    return getDisplayTimeBySeconds(duration);
}
